package edu.hncj.seckill.controller;

import edu.hncj.seckill.domain.User;
import edu.hncj.seckill.domain.UserPassword;
import edu.hncj.seckill.model.UserModel;
import edu.hncj.seckill.response.Result;
import edu.hncj.seckill.service.SmsSerive;
import edu.hncj.seckill.service.UserPasswordService;
import edu.hncj.seckill.service.UserService;
import edu.hncj.seckill.utils.Md5Utils;
import edu.hncj.seckill.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author anorak
 */
@CrossOrigin
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserPasswordService userPasswordService;

    @Autowired
    SmsSerive smsSerive;

    @RequestMapping("/")
    public String main1(){
        return "index";
    }

    /**
     * 修改信息
     * @param username 用户名
     * @param phone 手机号
     * @param sex 性别
     * @return 返回提示结果
     */
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    @ResponseBody
    @RequestMapping("/updateinfo")
    public Result upData(@RequestParam(name = "username")String username,@RequestParam(name = "phone")String phone,@RequestParam(name = "sex")String sex){
        // 根据手机号去数据库查询用户
        User user = userService.getUserByTelPhone(phone);
        user.setName(username);
        user.setGender(Integer.parseInt(sex));
        //  更新数据
        int a = userService.updateUserById(user);
        // 创建返回对象
        Map<String,Object> map = new HashMap<>(2);
        if (a == 1){
            map.put("code",26);
            map.put("ms","更新数据成功,请重新登录！");
        }else{
            map.put("code",27);
            map.put("ms","更新数据失败！");
        }
        return Result.create(map);
    }


    /**
     * 修改密码
     * @param password 密码
     * @param phone 手机号
     * @return 返回提示结果
     */
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    @ResponseBody
    @RequestMapping("/updateinfopass")
    public Result upDataPass(@RequestParam(name = "password")String password,@RequestParam(name = "phone")String phone){
        // 根据手机号去数据库查询用户
        User user = userService.getUserByTelPhone(phone);
        // 根据用户ID查询密码对象
        UserPassword userPassword = userPasswordService.selectByUserId(user.getId());
        // 设置密码
        userPassword.setPassword(Md5Utils.encrypt(password));
        int a = userPasswordService.updateUserPasswordByUserId(userPassword);
        Map<String,Object> map = new HashMap<>(2);
        if (a == 1){
            map.put("code",26);
            map.put("ms","更新数据成功,请重新登录！");
        }else{
            map.put("code",27);
            map.put("ms","更新数据失败！");
        }
        return Result.create(map);
    }

    @ResponseBody
    @RequestMapping("/get")
    public Result getUser(@RequestParam(name = "id")String id){
        // 调用Service方法
        UserModel model = userService.getUserById(id);
        System.out.println("yes");
        return Result.create(convertFromDataObject(model));
    }

    /**
     *  用户登录
     * @param telephone 手机号
     * @param password 密码
     * @return 结果
     */
    @ResponseBody
    @RequestMapping("/signin")
    public Result signInUser(@RequestParam(name = "telephone")String telephone, @RequestParam(name = "password")String password){
        // 根据手机号去数据库查询用户
        User user = userService.getUserByTelPhone(telephone);
        // 创建返回对象
        Map<String,Object> map = new HashMap<>(2);
        if (user == null){
            // 手机号不对
            map.put("code",7);
            map.put("ms","该账号尚未注册,请您先注册账号！");
        }else{
            // 根据用户Id查找密码对象
            UserPassword userPassword = userPasswordService.selectByUserId(user.getId());
            if (userPassword == null){
                map.put("code",8);
                map.put("ms","该账号异常,请联系管理员！");
            }else{
                // 对比密码
                if (Md5Utils.checkEncrypt(password,userPassword.getPassword())){
                    // 密码正确并把用户对象传到前端
                    map.put("user", user);
                    map.put("code",9);
                    map.put("ms","校验成功,马上登录！");
                }else{
                    // 密码错误
                    map.put("code",10);
                    map.put("ms","您输入的账号或密码有误！");
                }
            }
        }
        return Result.create(map);
    }

    /**
     *  短信登录
     * @param telephone 手机号
     * @param code 验证码
     * @return 结果
     */
    @ResponseBody
    @RequestMapping("/signbyphone")
    public Result signByPhone(@RequestParam(name = "telephone")String telephone,@RequestParam(name = "code")String code) throws Exception {
        // 根据手机号去数据库查询用户
        User user = userService.getUserByTelPhone(telephone);
        // 创建返回对象
        Map<String,Object> map = new HashMap<>(2);
        if (user == null){
            // 手机号不对
            map.put("code",14);
            map.put("ms","该手机尚未注册,请您先注册账号！");
        }else{
            // 根据手机号和验证码去校验
            String ms = smsSerive.checkCode(telephone, code);
            String flag = "ok";
            if (ms.contains(flag)){
                // 短信验证通过并把用户对象传到前端
                map.put("user", user);
                map.put("code",15);
                map.put("ms","短信验证校验通过,登录成功！");
            }else{
                map.put("code",16);
                map.put("ms"," 您短信验证码不正确!");
            }
        }
        return Result.create(map);
    }

    /**
     * 验证短信码同时注册用户
     * @param username 用户名
     * @param password 密码
     * @param phone_number 用户正在注册的手机号
     * @param code 验证码
     * @return 返回提示结果
     */
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    @ResponseBody
    @RequestMapping("/signup")
    public Result regUser(@RequestParam(name = "username")String username,@RequestParam(name = "password")String password,@RequestParam(name = "phone_number")String phone_number,@RequestParam(name = "code")String code) throws Exception {
        // 先对用户输入的验证码校验
        String ms = smsSerive.checkCode(phone_number, code);
        System.out.println(ms);
        // 创建返回对象
        Map<String,Object> map = new HashMap<>(2);
        String flag = "ok";
        if (ms.contains(flag)){
            // 可以认为验证通过,准备进行注册了
            // 整理拿着手机号去数据库查询是否已经存在如果不存在就算了，如果存在就返回提示
            User user = userService.getUserByTelPhone(phone_number);
            // 如果确认无注册记录,就开始注册了
            if (user == null){
                // 生成uuid作为主键
                String id = UUID.randomUUID().toString().replace("-", "");
                // 创建存储对象
                User userReg = new User();
                userReg.setId(id);
                userReg.setName(username);
                userReg.setTelphone(phone_number);
                // 性别先设置为未知
                userReg.setGender(0);
                // 准备插入用户数据
                int u = userService.insertUser(userReg);
                // 插入密码
                UserPassword userPassword = new UserPassword();
                userPassword.setUserId(id);
                userPassword.setPassword(Md5Utils.encrypt(password));
                int p = userPasswordService.insertUserPassword(userPassword);
                if (u != 1 && p != 1){
                    map.put("code",5);
                    map.put("ms","发生未知错误,请您稍后再试！");
                }else{
                    map.put("code",6);
                    map.put("ms","注册成功,正在跳转登录！");
                }
            }else {
                map.put("code",1);
                map.put("ms","该手机号已经被注册，请直接登录！");
            }
        }else{
            map.put("code",4);
            map.put("ms","您短信验证码不正确!");
        }
        return Result.create(map);
    }

    /**
     * 前端传入的手机号
     * @param telPhone 用户正在注册的手机号
     * @return 返回提示结果
     */
    @ResponseBody
    @RequestMapping("/telephone")
    public Result telephone(@RequestParam(name = "telPhone")String telPhone) throws Exception {
        // 整理拿着手机号去数据库查询是否已经存在如果不存在就算了，如果存在就返回提示
        User user = userService.getUserByTelPhone(telPhone);
        // 创建返回对象
        Map<String,Object> map = new HashMap<>(2);
        if (user == null){
            // 确认数据库中没有这个手机号就发送短信给该手机,并对返回结果进行解析识别其是否发送成功
            String ms = smsSerive.sendSms(telPhone, "相关");
            System.out.println(ms);
            String flag = "smsId";
            if (ms.contains(flag)){
                map.put("code",2);
                map.put("ms","验证码已发送,请注意查看!");
            }else{
                map.put("code",3);
                map.put("ms","验证码发送失败,请稍后再试!");
            }
        }else{
            map.put("code",1);
            map.put("ms","该手机号已经被注册，请直接登录！");
        }
        return Result.create(map);
    }

    /**
     * 检查前端传来的手机号
     * @param telPhone 用户短信登录的手机号
     * @return 返回提示结果
     */
    @ResponseBody
    @RequestMapping("/telephonelogin")
    public Result telephonelogin(@RequestParam(name = "telPhone")String telPhone) throws Exception {
        // 整理拿着手机号去数据库查询是否已经存在如果存在就打算发送验证码，如果不存在就返回提示
        User user = userService.getUserByTelPhone(telPhone);
        // 创建返回对象
        Map<String,Object> map = new HashMap<>(2);
        if (user != null){
            // 已经确定数据库中存在该账户,准备发送验证码
            String ms = smsSerive.sendSms(telPhone, "相关");
            System.out.println(ms);
            String flag = "smsId";
            if (ms.contains(flag)){
                map.put("code",13);
                map.put("ms","验证码已发送,请注意查看!");
            }else{
                map.put("code",12);
                map.put("ms","验证码发送失败,请稍后再试!");
            }
        }else{
            map.put("code",11);
            map.put("ms","该手机号尚未注册，请先进行注册！");
        }
        return Result.create(map);
    }


    /**
     * 将模型对象转换为视图对象，过滤敏感信息
     * @param model 用户的模型对象，包含所有数据
     * @return 视图对象
     */
    private UserVo convertFromDataObject(UserModel model){
        if (model == null){
            return null;
        }
        UserVo userVo = new UserVo();
        userVo.setId(model.getId());
        userVo.setName(model.getName());
        switch(model.getGender()){
            case 1 :
                userVo.setGender("男");
                break;
            case 2 :
                userVo.setGender("女");
                break;
            default:
                userVo.setGender("未知");
                break;

        }
        userVo.setTelPhone(model.getTelPhone());
        return userVo;
    }

}